package space.jamestang.simpleci.config

import com.fasterxml.jackson.core.JsonParseException
import space.jamestang.simpleci.globalJsonConverter
import space.jamestang.simpleci.globalLogger
import java.nio.file.Path
import kotlin.io.path.createDirectory
import kotlin.io.path.createFile
import kotlin.io.path.notExists
import kotlin.io.path.outputStream
import kotlin.system.exitProcess

object ConfigChecker {

    private var configLocation: String = "config.json"
    lateinit var config: Config

    fun setConfigLocation(location: String){
        configLocation = location
    }

    fun check(){

        try {
            val configFile = Path.of(configLocation)
            if (configFile.notExists()){

                configFile.createFile().outputStream().bufferedWriter(Charsets.UTF_8).use { writer ->
                    writer.write(globalJsonConverter.writeValueAsString(Config("", "", "", 0)))
                }
                exitProcess(1)
            }


            try {
                config = globalJsonConverter.readValue(configFile.toFile(), Config::class.java)
            }catch (_: JsonParseException){
                globalLogger.error("配置文件损坏, 程序退出")
                exitProcess(1)
            }
        }catch (e: Exception){
            globalLogger.error(e.message)
        }

        checkDir()
    }


    private fun checkDir(){
        val baseDir = Path.of(config.baseDir!!)
        val logDir = Path.of(config.logDir!!)
        val buildDir = Path.of(config.buildDir!!)
        val repoDir = Path.of(config.reposDir!!)
        val buildToolsDir = Path.of(config.buildToolsPath!!)

        if (baseDir.notExists()) baseDir.createDirectory()
        if (logDir.notExists()) logDir.createDirectory()
        if (buildDir.notExists()) buildDir.createDirectory()
        if (repoDir.notExists()) repoDir.createDirectory()
        if (buildToolsDir.notExists()) buildToolsDir.createDirectory()

    }
}
